<?php

namespace app\merchant\controller;

use app\common\controller\Common;
use app\common\model\Member;
use app\common\model\Merchant;
use app\common\model\ReferralCode;
use app\common\model\Smscode;
Use app\common\model\Users;
use asms\Alisms;
use wx\Wechat;
use geohash\Geohash;
use think\db;
use wx\Wxapp;

class Index extends Common
{
    public function index()
    {
        $retype=request()->param('retype');
        $openid = request()->param('openid');
        $code = request()->param('code');
        if (is_null($code) || $code == "") {//再次访问
            if (is_null($openid) || $openid == "") return $this->errJson('参数错误');
            $user = new Users();
            $data_user = $user->where('openid', '=', $openid)->find();
            if (empty($data_user)) return $this->errJson('数据异常');
            //判断是否注册
            $retMe = Merchant::where('openid', '=', $openid)->find();
            if (empty($retMe)){
                return $this->okJson('未注册',['isRreg'=>-1,'openid'=>$openid]);
            }else{
                $data=[
                    'merid'=>$retMe->merid,
                    'status'=>$retMe->status,
                    'openid'=>$openid
                ];
                //查询注册状态
                if ($retMe->status == 2) return $this->okJson('青檬欢迎您',$data);
                if ($retMe->status == -1) return $this->okJson('您已提交申请，正在审核中',$data);
                if ($retMe->status == 4) return $this->okJson('您的帐号已被冻结！',$data);
            }
        }
        //第一次请求

        if ($retype=='wxapp'){
            $wxapp=new Wxapp();
            $reuser_info =$wxapp->getUser_info($code);
        }else{
            $wx = new Wechat();
            $reuser_info = $wx->getUser_info($code,false);
        }
        if ($reuser_info['flag'] == 0) return $this->errJson('数据异常');
        $user_info = $reuser_info['data'];
        $user_openid = $user_info['openid'];
        // 判断用户是否存在
        $user = new Users();
        $data_user = $user->where('openid', '=', $user_openid)->find();
        if (!empty($data_user)) {
            //判断是否注册
            $retMe = Merchant::where('openid', '=', $user_openid)->find();
            if (empty($retMe)){
                return $this->okJson('未注册',['isRreg'=>-1,'openid'=>$user_openid]);
            }else{
                $data=[
                    'merid'=>$retMe->merid,
                    'status'=>$retMe->status,
                    'openid'=>$user_openid
                ];
                //判断是否已开通会员卡,未开通
                if ($retMe->status == -1) return $this->okJson('您已提交申请，正在审核中', $data);
                if ($retMe->status == 2) return $this->okJson('青檬欢迎您', $data);
                if ($retMe->status == 4) return $this->okJson('您的帐号已被冻结！',$data);
            }

        } elseif (empty($data_user)) {//用户表没有主记录
            $udatas = [
                'username' => $user_info->nickname,
                'openid' => $user_openid,
                'headimgurl' => $user_info->headimgurl,
                'province' => $user_info->province,
                'ctime' => time(),
            ];
            $user = new Users();
            $rets = $user->create($udatas);
            if ($rets) {
                return $this->okJson('未注册', ['isRreg'=>-1,'openid'=>$user_openid]);
            }
            return $this->errJson('数据异常');
        }

    }

    //生成推荐二维码
    public function getRefcode()
    {
        $openid = request()->param('openid');
        $ret = Merchant::where('openid','=',$openid)->field('merid')->find();
        if (empty($ret)) return $this->errJson('数据异常');
        $reRef =ReferralCode::where(['merid'=>$ret->merid,'status'=>-1])->find();//找出一个状态为-1，未使用的推荐码，
        if (empty($reRef)){//如果不存在，未使用用的推荐码，就创建一个
            $rdatas=[
                'ref_code'=>$code = rand(11111, 99999).$ret->merid, //生成随机推荐码
                'merid'=>$ret->merid,
            ];
            $reRef = ReferralCode::create($rdatas);
            if (empty($retRef)) return $this->errJson('数据异常');
        }
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            $scheme = 'https://';
        } else {
            $scheme = 'http://';
        }
        $url = $scheme."mcarplus.qingmengcar.com?ref_code=" . $reRef->ref_code;
        return $this->okJson('ok', $url);
    }

    //开通注册会员
    public function register()
    {
        $mobile = request()->param('mobile');
        $mername = request()->param('mername');
        $vcode = request()->param('vcode');
        $openid = request()->param('openid');
        if ($mobile == "" || $mobile == null) return $this->errJson('请输入手机号');
        if ($vcode == "" || $vcode == null) return $this->errJson('请输入验证码');
        if ($openid == "" || $openid == null) return $this->errJson('缺少参数！');
        if ($mername == "" || $mername == null) return $this->errJson('请输入商家姓名');
        $ret = Smscode::where(['mobile' => trim($mobile), 'code' => trim($vcode)])->find();
        if ($ret) {
            $dtime = time() - $ret->time;
            if ($dtime / 60 > 12) return $this->errJson('验证码超时');

            $Merchant = new Merchant();
            $resMe = $Merchant->where('openid', '=', $openid)->find();
            if ($resMe) return $this->errJson('您已提交过申请了！');
            $data = [
                'mobile' => $mobile,
                'mername' => $mername,
                'openid' => $openid,
                'retime' => time(),
                'update' => time(),
            ];
            $res = Merchant::create($data);
            if (empty($res)) return $this->errJson('注册失败');
            return $this->okJson('您已提交申请，正在审核中');
        }
        return $this->errJson('手机号或验证码有误');

    }

    //发送验码
    public function sendSms()
    {
        $mobile = input('mobile');
        $openid = input('openid');
        if (is_null($mobile)||$mobile=="") return $this->errJson('手机号不能为空');
        $reSms = Smscode::where('mobile','=',$mobile)->order('time','desc')->find();
        if (!empty($reSms)){
            $dtime = time() - $reSms->time;
            if ($dtime < 60) return $this->errJson('60秒内只发送一次');
        }
        $sms = new Alisms();
        $ret = $sms->send($mobile);
        if ($ret['Code'] == 'OK') {
            $Smscode = new Smscode();
            $res = $Smscode->save([
                'mobile' => $mobile,
                'code' => $ret['code'],
                'time' => time()
            ]);
            if ($res) return $this->okJson('短信已发送');
        }
        return $this->errJson($ret['Message']);
    }

    //推广记录
    public function promotionrecord()
    {
        $openid = request()->param('openid');
        $reMer = Merchant::field('merid')->where('openid','=',$openid)->find();
        if ($openid == "" || $openid == null) return $this->errJson('缺少参数');
        if(empty($reMer)) return $this->errJson('数据异常');
        $merid=$reMer->merid;
        $page = $this->getPage();
        $pagesize = $this->getPageSize();
        $min = ($page - 1) * $pagesize;
        $max = $pagesize;
        $count = ReferralCode::where('merid', '=', $merid)->count();
        $verf = Db::query("SELECT mem.name,(case when rec.status=1 then '已注册' when rec.status =2 then '已开卡' end) as status, FROM_UNIXTIME(rec.reg_time) as time  FROM referral_code as rec JOIN member as mem on mem.memid=rec.memid WHERE rec.merid=" . $merid . " limit " . $min . "," . $max);
        if (count($verf) == 0) return $this->errJson('暂无返回记录');
        return $this->listJson($verf, $count);
    }

}